// src/main/java/com/bookmanager/dao/ProfileDAO.java
package com.bookmanager.dao;

import com.bookmanager.model.UserProfile;
import com.bookmanager.util.DatabaseUtil;
import java.sql.*;

public class ProfileDAO {

    public UserProfile getUserProfile(String userId) {
        UserProfile userProfile = null;

        // 获取用户基本信息
        String userSql = "SELECT * FROM users WHERE user_id = ?";

        try (Connection conn = DatabaseUtil.getConnection();
             PreparedStatement userStmt = conn.prepareStatement(userSql)) {

            userStmt.setString(1, userId);
            ResultSet userRs = userStmt.executeQuery();

            if (userRs.next()) {
                userProfile = new UserProfile();
                userProfile.setUserId(userRs.getString("user_id"));
                userProfile.setUsername(userRs.getString("username"));
                userProfile.setEmail(userRs.getString("email"));
                userProfile.setPhone(userRs.getString("phone"));
                userProfile.setRole(userRs.getString("role"));

                Timestamp createTime = userRs.getTimestamp("create_time");
                if (createTime != null) {
                    userProfile.setCreateTime(createTime.toLocalDateTime());
                }

                // 获取统计信息
                setUserStatistics(conn, userProfile, userId);
            }

        } catch (SQLException e) {
            e.printStackTrace();
        }

        return userProfile;
    }

    private void setUserStatistics(Connection conn, UserProfile userProfile, String userId) throws SQLException {
        // 获取总借阅数量
        String borrowSql = "SELECT COUNT(*) FROM borrow_records WHERE user_id = ?";
        try (PreparedStatement stmt = conn.prepareStatement(borrowSql)) {
            stmt.setString(1, userId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                userProfile.setBorrowCount(rs.getInt(1));
            }
        }

        // 获取当前借阅数量
        String currentBorrowSql = "SELECT COUNT(*) FROM borrow_records WHERE user_id = ? AND status = 'borrowed'";
        try (PreparedStatement stmt = conn.prepareStatement(currentBorrowSql)) {
            stmt.setString(1, userId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                userProfile.setCurrentBorrows(rs.getInt(1));
            }
        }

        // 获取收藏数量
        String favoriteSql = "SELECT COUNT(*) FROM favorites WHERE user_id = ?";
        try (PreparedStatement stmt = conn.prepareStatement(favoriteSql)) {
            stmt.setString(1, userId);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                userProfile.setFavoriteCount(rs.getInt(1));
            }
        }
    }
}